<template>
  <div class="chat">
    <div class="chat-content" ref="customDiv">
      <div v-for="(item, index) in dhList" :key="index">
        <div class="left-text" v-if="item.type == 'l'">
          <div class="usericon">
            <img src="@/assets/images/video/jqr.png" />
          </div>
          <div class="text-box">
            <div v-html="item.content"></div>
          </div>
          <div
            class="panelbtns"
            v-for="item in item.btns"
            :class="{ active: currentType == item.id }"
            :key="item.id"
            @click="currentType = item.id"
          >
            {{ item.name }}
          </div>
          <!-- 操作按钮 -->
          <div
            class="bototm-panel"
            v-if="
              item.type == 'l' &&
              index == dhList.length - 1 &&
              index !== 0 &&
              item.list
            "
          >
            <span class="btns" @click="emitPoint(item.list)">
              <!-- <img class="copypng" src="../assets/images/copy.png" /> -->
              <span>视频上屏</span>
            </span>
            <!-- <span class="btns">
              <img class="copypng" src="../assets/images/refresh.png" />
              <span>重新生成</span>
            </span> -->
          </div>
          <div class="echarts-content" v-if="item.list">
            <treeEcharts
              :options="item.list"
              @emitPoint="onePlay"
              @playAll="emitPoint(item.list)"
            ></treeEcharts>
          </div>
        </div>
        <div class="right-text" v-if="item.type == 'r'">
          <div class="text-box">
            <div v-html="item.content"></div>
            <!-- <img v-if="item.audioUrl" :src="item.audioUrl" /> -->
            <p v-if="item.audioUrl" @click="speakUrl(item.audioUrl)">
              点击播放语音
            </p>
          </div>
          <div class="usericon">
            <img src="@/assets/images/video/user.png" />
          </div>
        </div>
      </div>
    </div>
    <div class="stop-btn" v-if="isloading && false" @click="stopTosend">
      <!-- <img src="../assets/images/stop.png" /> -->
      <span>停止生成</span>
    </div>
    <div class="chat-input">
      <el-input
        class="speekinput"
        placeholder="有问题尽管问我～"
        @keyup.enter="handleEnter"
        v-model="speak"
        type="textarea"
        resize="none"
      />
      <div class="send-box">
        <img
          class="sendimg"
          @click="handleEnter"
          v-if="!isloading"
          src="@/assets/images/video/send.png"
        />
      </div>
    </div>
    <audio ref="alarmSound" :src="currentspeakUrl"></audio>
  </div>
</template>

<script setup>
import { onMounted } from "vue";
import treeEcharts from "@/components/treeEcharts.vue";
import { sendMessage as sendMessageApi } from "@/api/chat.js";
const emit = defineEmits(["emitAllPoint"]);
let speak = ref("");
let isloading = ref(false);
let currentType = ref("camera_area");
let dhList = ref([
  {
    type: "l",
    tips: '例如："查找新港社区的所有监控"，"显示昨天XX街发生交通事故的视频点位”',
    btns: [
      // {
      //   name: "场所定位：调取XX社区正门监控",
      //   id: "camera_area",
      // },
      // // {
      // //   name: "事件追溯：调取昨天下午新园路占道经营视频",
      // //   id: "area",
      // // },
      // {
      //   name: "场景检索：展示防汛场景视频",
      //   id: "camera_scene",
      // },
      // {
      //   name: "算法检索：查找具备占道经营分析能力的视频设备",
      //   id: "camera_arithmetic",
      // },
    ],
    content:
      "您好，我是智能视频检索助手，您可以通过文字或语音告诉我您想查看的视频监控设备！",
  },
]);
const typeText = (content, idx) => {
  return new Promise((resolve, reject) => {
    dhList.value[idx].content = "";
    let shan =
      "<span style='margin-left:5px;background-color:#1b97f1;'>&nbsp;</span>";
    let len = shan.length;
    let index = 0; // 当前正在输出的单词索引
    let randomNum = 100;
    dhList.value[idx].type = "l";
    let interval = setInterval(() => {
      scrollToBottom();
      randomNum = Math.floor(Math.random() * (61 - 50) + 70);
      if (index === content.length) {
        dhList.value[idx].content = dhList.value[idx].content.substring(
          0,
          dhList.value[idx].content.length - len
        );
        clearInterval(interval); // 所有单词都已经输出完毕时清除计时器
        scrollToBottom();
        resolve();
      } else {
        if (dhList.value[idx].content.length > 0) {
          dhList.value[idx].content = dhList.value[idx].content.substring(
            0,
            dhList.value[idx].content.length - len
          );
        }
        dhList.value[idx].content += content[index]; // 将当前单词添加到显示内容中
        index++; // 更新索引值
        dhList.value[idx].content += shan;
      }
    }, 50); // 每500ms输出一个单词
  });
};

const outmsg2 = async (content, result) => {
  let se = content
    .replaceAll("\\n", "\n")
    .replaceAll("\n\n", "<br/>")
    .replaceAll("\n", "<br/>");

  scrollToBottom();
  dhList.value.push({
    type: "r",
    content: se,
    list: result,
    // list: [
    //   {
    //     name: "新开里小区",
    //     id: "1",
    //     level: "1",
    //     parentId: "",
    //   },
    //   {
    //     name: "新开里小区西门",
    //     id: "1-1",
    //     level: "2",
    //     parentId: "1",
    //   },
    //   {
    //     name: "西门出入口",
    //     id: "1-1-1",
    //     level: "3",
    //     parentId: "1-1",
    //   },
    //   {
    //     name: "场景出入口",
    //     id: "1-1-2",
    //     level: "3",
    //     parentId: "1-1",
    //   },

    //   {
    //     name: "新开里小区东门",
    //     id: "1-2",
    //     level: "2",
    //     parentId: "1",
    //   },
    //   {
    //     name: "东门小区出入口",
    //     id: "1-2-1",
    //     level: "3",
    //     parentId: "1-2",
    //   },
    //   {
    //     name: "东门场景出入口",
    //     id: "1-2-2",
    //     level: "3",
    //     parentId: "1-2",
    //   },
    // ],
  });
  await typeText(
    dhList.value[dhList.value.length - 1].content.split(""),
    dhList.value.length - 1
  );
};

const customDiv = ref();
const scrollToBottom = () => {
  nextTick(() => {
    if (customDiv.value) {
      customDiv.value.scrollTop = customDiv.value.scrollHeight;
    }
  });
};

let alarmSound = ref();
let currentspeakUrl = ref("");
const speakUrl = (url) => {
  currentspeakUrl.value = url;
  alarmSound.value.play();
};

// 发语音
const sendMessage = async (speakUrl) => {
  dhList.value.push({
    type: "r",
    content: "",
    audioUrl: speakUrl,
  });
};

let currentUser = ref({ conversationId: "" });
const handleEnter = async () => {
  if (isloading.value) return;
  try {
    if (!speak.value) return;
    isloading.value = true;
    dhList.value.push({
      type: "r",
      content: speak.value,
    });
    dhList.value.push({
      type: "l",
      content: "正在解析...",
    });
    let sendtext = speak.value;
    speak.value = "";
    let { data } = await sendMessageApi({
      query: sendtext,
      conversationId: currentUser.value.conversationId || "",
      user: "123456789",
      // tagGroupCode: currentType.value,
    });
    // let data = {
    //   event: "message",
    //   messageId: "87610755-f9ff-4982-b04b-4cd91b66530e",
    //   conversationId: "441152b4-e17f-44ad-b963-8b284808767e",
    //   mode: "advanced-chat",
    //   answer:
    //     '```json\n{\n  "bodyStr": "{\\"result\\": \\"{\\\\\\"errorCode\\\\\\":\\\\\\"0\\\\\\",\\\\\\"data\\\\\\":{\\\\\\"tagId\\\\\\":\\\\\\"1904716438673952772\\\\\\",\\\\\\"tagName\\\\\\":\\\\\\"人脸抓拍入口\\\\\\",\\\\\\"tagDevices\\\\\\":[{\\\\\\"camera\\\\\\":\\\\\\"和睦里小区14号楼南向北球机117\\\\\\",\\\\\\"deviceId\\\\\\":\\\\\\"1889988682998511328\\\\\\",\\\\\\"tags\\\\\\":null},{\\\\\\"camera\\\\\\":\\\\\\"和睦里小区14号楼南向北球机117\\\\\\",\\\\\\"deviceId\\\\\\":\\\\\\"1889988682998511328\\\\\\",\\\\\\"tags\\\\\\":[{\\\\\\"tagId\\\\\\":\\\\\\"1902673290191835136\\\\\\",\\\\\\"tagName\\\\\\":\\\\\\"小区内\\\\\\"}]},{\\\\\\"camera\\\\\\":\\\\\\"和睦里小区14#楼北向南枪机106\\\\\\",\\\\\\"deviceId\\\\\\":\\\\\\"1889988737107237536\\\\\\",\\\\\\"tags\\\\\\":[{\\\\\\"tagId\\\\\\":\\\\\\"1904716438673952772\\\\\\",\\\\\\"tagName\\\\\\":\\\\\\"人脸抓拍入口\\\\\\"}]},{\\\\\\"camera\\\\\\":\\\\\\"和睦里小区14#楼北向南枪机106\\\\\\",\\\\\\"deviceId\\\\\\":\\\\\\"1889988737107237536\\\\\\",\\\\\\"tags\\\\\\":[{\\\\\\"tagId\\\\\\":\\\\\\"1902673290191835136\\\\\\",\\\\\\"tagName\\\\\\":\\\\\\"小区内\\\\\\"}]}]},\\\\\\"message\\\\\\":\\\\\\"操作成功\\\\\\"}\\"}",\n  "aiAnswer": "人脸抓拍入口的摄像头是：和睦里小区14#楼北向南枪机106。"\n}\n```',
    //   body: {
    //     result: {
    //       errorCode: "0",
    //       data: {
    //         tagId: "1904716438673952772",
    //         tagName: "人脸抓拍入口",
    //         tagDevices: [
    //           {
    //             deviceId: "1889988682998511328",
    //             camera: "和睦里小区14号楼南向北球机117",
    //             tags: null,
    //           },
    //           {
    //             deviceId: "1889988682998511328",
    //             camera: "和睦里小区14号楼南向北球机117",
    //             tags: [
    //               {
    //                 tagId: "1902673290191835136",
    //                 tagName: "小区内",
    //               },
    //             ],
    //           },
    //           {
    //             deviceId: "1889988737107237536",
    //             camera: "和睦里小区14#楼北向南枪机106",
    //             tags: [
    //               {
    //                 tagId: "1904716438673952772",
    //                 tagName: "人脸抓拍入口",
    //               },
    //             ],
    //           },
    //           {
    //             deviceId: "1889988737107237536",
    //             camera: "和睦里小区14#楼北向南枪机106",
    //             tags: [
    //               {
    //                 tagId: "1902673290191835136",
    //                 tagName: "小区内",
    //               },
    //             ],
    //           },
    //         ],
    //       },
    //       message: "操作成功",
    //     },
    //   },
    //   aiAnswer: "人脸抓拍入口的摄像头是：和睦里小区14#楼北向南枪机106。",
    //   createdAt: 1744874919,
    // };
    if (!currentUser.value.conversationId) {
      currentUser.value.conversationId = data.conversationId;
    }

    dhList.value.pop();
    scrollToBottom();
    setTimeout(() => {
      outmsg2(
        // `API调用: 你可以继续提问?\n1、新开里小区。\n 2、近开里小区点位。`
        `${data.aiAnswer}`,
        data.body.result.data
      );
    }, 30);
    isloading.value = false;
  } catch (e) {
    speak.value = "";
    isloading.value = false;
    console.error(e);
  }
};

const stopTosend = () => {
  isloading.value = false;
};

async function copyText(text) {
  try {
    // 使用 Clipboard API 写入文本
    await navigator.clipboard.writeText(text);
    console.log("已复制文本：", text);
  } catch (err) {
    console.error("复制失败：", err);
  }
}

// 向父组件提交点位
const emitPoint = async (list) => {
  try {
    let pointIds = [];
    list.tagDevices.forEach((element) => {
      pointIds.push(element.cameraIndexCode);
    });
    emit("emitAllPoint", pointIds);
  } catch (e) {
    console.error(e);
  }
};
// 向父组件提交点位
const onePlay = async (value) => {
  try {
    emit("emitAllPoint", [value]);
  } catch (e) {
    console.error(e);
  }
};

onMounted(() => {
  scrollToBottom();
});
</script>


<style lang="scss">
.chat {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .chat-content {
    width: 100%;
    flex: 1;
    padding: 27px 0px;
    overflow-y: auto;
    position: relative;

    .left-text {
      width: 100%;
      padding-left: 30px;
      .usericon {
        display: inline-block;
        vertical-align: top;
        margin-right: 15px;
        img {
          width: 37px;
          height: 34px;
        }
      }
      .text-box {
        margin-top: 8px;
        display: inline-block;
        vertical-align: top;
        max-width: 320px;
        min-height: 44px;
        background: #fff;
        box-shadow: 0px 0px 29px 0px rgba(70, 102, 149, 0.06);
        border-radius: 6px;
        line-height: 20px;
        padding: 12px 21px 12px 18px;
        .tips {
          margin-top: 16px;
          width: 100%;
          font-size: 20px;
          color: #b6d6ff;
          line-height: 30px;
          padding: 16px;
          background: rgba(0, 49, 115, 0.6);
          border-radius: 12px;
        }
      }

      .panelbtns {
        margin: 5px 0;
        margin-left: 50px;
        width: 320px;
        height: 36px;
        background: #e4effd;
        border-radius: 8px;
        border: 1px solid #c3dcff;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 12px;
        color: #666666;
        padding: 0 16px;
        line-height: 36px;
        cursor: pointer;
        &.active {
          color: #27c8ff;
        }
        &:hover {
          color: #27c8ff;
        }
      }
      .echarts-content {
        margin: 15px 0;
        margin-left: 18px;
        width: 330px;
        height: 300px;
      }
    }
    .right-text {
      margin-top: 25px;
      margin-bottom: 25px;
      width: 100%;
      text-align: right;
      .usericon {
        display: inline-block;
        vertical-align: top;
        img {
          width: 36px;
          height: 36px;
          margin-right: 25px;
        }
      }
      .text-box {
        margin-top: 8px;
        display: inline-block;
        vertical-align: top;
        max-width: 270px;
        min-height: 44px;
        background: #ffffff;
        box-shadow: 0px 0px 29px 0px rgba(70, 102, 149, 0.06);
        border-radius: 6px;
        line-height: 20px;
        padding: 12px 21px 12px 18px;
        text-align: left;
        margin-right: 15px;
        word-break: break-all;
      }
    }

    .bototm-panel {
      margin-top: 12px;
      margin-left: 56px;
      width: 90px;
      height: 36px;
      background: #2263bf;
      border-radius: 8px;
      text-align: center;
      line-height: 36px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 12px;
      color: #ffffff;
      cursor: pointer;
    }
  }
  .stop-btn {
    width: 95px;
    height: 30px;
    text-align: center;
    cursor: pointer;
    background: rgba(34, 126, 255, 0.1);
    border-radius: 4px;
    border: 1px solid rgba(34, 99, 191, 0.15);
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 14px;
    color: #2263bf;
    line-height: 30px;
    position: absolute;
    bottom: 120px;
    left: 241px;
    display: flex;
    align-items: center;
    padding: 0 8px;
    cursor: pointer;
    z-index: 999;
    img {
      margin-right: 4px;
    }
  }

  .chat-input {
    width: 100%;
    height: 80px;
    margin-bottom: 30px;
    padding: 0 40px 0 40px;
    position: relative;
    .speekinput {
      width: 100%;
      height: 80px;
      box-shadow: 0px 0px 29px 0px rgba(70, 102, 149, 0.18);
      border-radius: 6px;
      background: #fff;
      .el-textarea__inner {
        height: 50px;
        border: 0;
        box-shadow: none;

        &::-webkit-scrollbar {
          width: 2px;
          height: 4px;
          // height: .04rem;
        }

        /*定义滚动条轨道 内阴影+圆角*/
        &::-webkit-scrollbar-track {
          border-radius: 0.03rem;
          /* background-color: rgb(255 255 255); */
          width: 2px;
        }

        /*定义滑块 内阴影+圆角*/
        &::-webkit-scrollbar-thumb {
          border-radius: 2px;
          background-color: #eee;
          border-radius: 2px;
          background: #ccc;
        }

        /*交叉方块*/
        &::-webkit-scrollbar-corner {
          background-color: rgb(255 255 255);
        }
      }
    }
  }
  .sendimg {
    width: 30px;
    height: 30px;
    position: absolute;
    right: 50px;
    bottom: 10px;
    cursor: pointer;
    z-index: 999;
  }
}
</style>